#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Fcntl.hpp"
#define QUEUE_NUM 20 // 监听队列长度
class Sock
{
public:
    Sock()
        : _listen_queue(QUEUE_NUM)
    {
        int sock = socket(AF_INET, SOCK_STREAM, 0); // 创建套接字
        if (sock < 0)
        {
            std::cout << "socket fail:" << strerror(errno) << std::endl;
            exit(1);
        }
        // 设置端口复用
        int opt = 1;
        setsockopt(sock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
        // 设置非阻塞读取
        _sock = sock;
        setblock(_sock);
    }
    void Bind(uint16_t port = 8080, const std::string &ip = "0.0.0.0")
    {
        sockaddr_in sever; // 创建sockaddr_in结构体
        memset(&sever, 0, sizeof sever);
        sever.sin_addr.s_addr = inet_addr(ip.c_str());
        sever.sin_port = htons(port);
        sever.sin_family = AF_INET;
        socklen_t len = sizeof sever;
        int ret = bind(_sock, (sockaddr *)(&sever), len); // 绑定
        if (ret < 0)
        {
            std::cout << "bind fail:" << strerror(errno) << std::endl;
            exit(2);
        }
    }
    int Listen()
    {
        int lret = listen(_sock, _listen_queue); // 监听
        if (lret < 0)
        {
            std::cout << "listen fail:" << strerror(errno) << std::endl;
            exit(3);
        }
        return _sock;
    }
    void Connect(int sock, uint16_t port, const std::string &ip)
    {
        sockaddr_in sever;
        memset(&sever, 0, sizeof sever);
        sever.sin_addr.s_addr = inet_addr(ip.c_str());
        sever.sin_port = htons(port);
        sever.sin_family = AF_INET;
        int ret = connect(sock, (sockaddr *)(&sever), sizeof sever);
        if (ret < 0)
        {
            std::cout << "connect fail:" << strerror(errno) << std::endl;
            exit(4);
        }
    }
    int Accept()
    {
        sockaddr_in client;
        memset(&client, 0, sizeof client);
        socklen_t len = sizeof client;
        int sock = accept(_sock, (sockaddr *)(&client), &len);
        if (sock > 0)
        {
            return sock;
        }
        return -1;
    }
    ~Sock()
    {
        if (_sock > 0)
            close(_sock);
    }
    int _sock; // 套接字
private:
    const int _listen_queue; // 监听队列长度
};
